package com.loveyukari.controller;

import com.loveyukari.model.Address;
import com.loveyukari.model.Auth;
import com.loveyukari.service.AddressService;
import com.loveyukari.service.AuthService;
import com.loveyukari.service.ManagerService;
import com.loveyukari.support.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/admin/address")
@Controller
public class AddressController {

    @Autowired
    private AddressService addressService;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String add(){
        return "address/add";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public String add(String name,String phone,String address, HttpServletRequest request){
        String sign =(String) request.getAttribute("sign");
        int authId = managerService.getManageAuthId(sign);
        addressService.addAuthAddress(address,name,phone,authId);
        return "redirect:/admin/address/list";
    }

    @RequestMapping("list")
    public String list(Model model,HttpServletRequest request){
        String sign =(String) request.getAttribute("sign");
        int authId = managerService.getManageAuthId(sign);
        List<Address> list = addressService.getAuthAddress(authId);
        Auth auth = authService.getCacheAuth(authId);
        model.addAttribute("authName",auth.getName());
        model.addAttribute("list",list);
        return "address/list";
    }

    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Integer id, HttpServletRequest request){
        String sign =(String) request.getAttribute("sign");
        int authId = managerService.getManageAuthId(sign);
        addressService.deleteAuthAddress(id,authId);
        return new JsonResult();
    }
}
